Is .collection() cheap? Because in the example below, a and b are not the same...
import { MongoClient } from "mongodb";
const mongoClient = new MongoClient('mongodb://localhost:27017', { useUnifiedTopology: true });
mongoClient.connect().then(client => {
const a = client.db("test").collection("demo");
const b = client.db("test").collection("demo");
console.log(a == b); // false
mongoClient.close();
});
Should we use a single .collection() instance all over the application?
Or is creating a .collection() cheap?
I think the line console.log(a == b); is returning False because a and b are two different unique cursors, which though have the same data, but have different unique addresses.
I think it isn't because .collection, its because client.db.
MongoDB Node driver is not single connection based. It uses connection pooling and the default poolSize is 5.
Since you try to connect the same database with different connections from connection pool, the cursor you're using is different aswell.
From my knowledge, you should create and use new collection objects from your database object, the moment you'll going to use it. If you use the same collection object for your every database operation, you'll end up using single database connection instead of multiple connections in connection pool.
And if you want you can increase the poolSize of MongoDB Node driver aswell.
You can check the other options from the docs aswell. http://mongodb.github.io/node-mongodb-native/3.6/api/MongoClient.html#.connect